// const url = 'http://api.douban.com/v2/movie/subject/26985127,';
const rp = require('request-promise-native');
const mongoose = require('mongoose');
const Movie = mongoose.model('Movie');
const Category = mongoose.model('Category');

async function fetchMovie(item) {
    const url = `http://api.douban.com/v2/movie/${item.doubanId}`;
    const res = await rp(url);
    let body;
    try {
        body = JSON.parse(res);
    } catch (err) {
        console.log(err);
    }
    return body;
}

;
(async () => {
    let movies = await Movie.find({
        // 查询条件
        $or: [
            { summary: { $exists: false } },
            { summary: null },
            { summary: '' },
            { title: '' },
            { year: { $exists: false }}
        ]
    })

    // for (let i = 0; i < [movies[0]].length; i++) { // 测试
    for (let i = 0; i < movies.length; i++) {
        let movie = movies[i];
        let movieData = await fetchMovie(movie);
        if (movieData) {
            let tags = movieData.tags || [];
            movie.tags = movie.tags || [];
            // tag
            tags.forEach(tag => movie.tags.push(tag.name));

            // summary
            movie.summary = movieData.summary || '';

            // title
            movie.title = movieData.title || '';

            // rawTitle
            movie.rawTitle = movieData.alt_title || movieData.title || '';

            if (movieData.attrs) {
                movie.movieTypes = movieData.attrs.movie_type || [];
                for (let i = 0; i < movie.movieTypes.length; i++) {
                    let item = movie.movieTypes[i];
                    // 检查分类 为分类添加相关电影的引用关系（一个分类对应多个电影）
                    let category = await Category.findOne({
                        name: item
                    })
                    if (!category) {
                        category = new Category({
                            name: item,
                            movies: [movie._id]
                        })
                    } else {
                        if (category.movies.indexOf(movie._id) === -1) {
                            category.movies.push(movie._id);
                        }
                    }
                    await category.save();

                    // 检查当前电影 为电影添加电影中分类的引用关系（一个电影可对应对个分类）
                    if (!movie.category) {
                        movie.category.push(category._id);
                    } else {
                        if (movie.category.indexOf(category._id) === -1) {
                            movie.category.push(category._id);
                        }
                    }
                }
                let dates = movieData.attrs.pubdate || [];
                let pubdates = [];
                dates.map(item => {
                    if (item && item.split('(').length > 0) {
                        // item格式：2018-08-10(美国)
                        let parts = item.split('(');
                        let date = parts[0]; // 上映日期
                        let country = '未知';
                        if (parts[1]) {
                            country = parts[1].split(')')[0]; // 上映国家
                        }

                        pubdates.push({
                            date: new Date(date),
                            country: country
                        })
                    }
                })
                // pubdate
                movie.pubdate = pubdates;

                // year
                movie.year = movieData.attrs.year[0] || '2500';
            }
            console.log(movie);
            await movie.save();
        }
    }
})();